class Solution:
    def minDominoRotations(self, A: list, B: list) -> int:
        def check(a, b, num):
            res_a = 0
            res_b = 0
            for i in range(len(A)):
                if A[i] != num and B[i] != num:
                    return -1
                if A[i] == num and B[i] != num:
                    res_b += 1
                if B[i] == num and A[i] != num:
                    res_a += 1

            return min(res_a, res_b)

        res = check(A, B, A[0])
        if res != -1 or A[0] == B[0]:
            return res
        return check(A, B, B[0])
